/*****************************
 * Copyright (c) 2008 by snzo Co. Ltd.  All rights reserved.
 ****************************/
package com.core.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.fileupload.FileItem;

/**
 * @{#} UploadUtils.java Create on Sep 10, 2008 3:45:04 PM
 * <p>
 * 上传文件工具类.
 * </p>
 * @author <a href="mailto:cwx714@hotmail.com">cuiwx</a>
 * @version v 0.1
 */
public class UploadUtils {
	
	public static final int BUFFERSIZE = 4096;
	
	private FileItem item;
	private String extension = "";

	/**
	 * 
	 * @param item
	 */
	public UploadUtils(FileItem item) {
		this.item = item;
	}

	/**
	 * 
	 * @return 扩展名
	 */
	public String getExtension() {
		if (this.extension == null || this.extension.equals("")) {
			this.extension = this.item.getName().substring(
					this.item.getName().lastIndexOf('.') + 1);
		}

		return this.extension;
	}

	/**
	 * 保存文件.
	 * @param filename
	 * @throws IOException io
	 */
	public void saveUploadedFile(String filename) throws IOException {
		BufferedInputStream inputStream = null;
		FileOutputStream outputStream = null;

		try {
			inputStream = new BufferedInputStream(this.item.getInputStream());
			outputStream = new FileOutputStream(filename);

			int c;
			byte[] b = new byte[BUFFERSIZE];
			while ((c = inputStream.read(b)) != -1) {
				outputStream.write(b, 0, c);
			}
		} finally {
			if (outputStream != null) {
				outputStream.flush();
				outputStream.close();
			}

			if (inputStream != null) {
				inputStream.close();
			}
		}
	}

	/**
	 * 保存文件.
	 * @param fileName
	 * @param file
	 * @throws IOException 无法创建文件.
	 */
	public static void saveFile(String fileName, File file) throws IOException {
		createPath(fileName);
		BufferedInputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			inputStream = new BufferedInputStream(new FileInputStream(file));
			outputStream = new FileOutputStream(fileName);

			int c;
			byte[] b = new byte[BUFFERSIZE];
			while ((c = inputStream.read(b)) != -1) {
				outputStream.write(b, 0, c);
			}
		} finally {
			if (outputStream != null) {
				outputStream.flush();
				outputStream.close();
			}

			if (inputStream != null) {
				inputStream.close();
			}
		}
	}

	/**
	 * 创建路径.
	 * @param fileName
	 */
	public static void createPath(String fileName) {
		int pathpos = fileName.lastIndexOf(File.separatorChar);
		String path = "";
		if (pathpos > 0) {
			path = fileName.substring(0, pathpos);
			File file = new File(path);
			if (!file.exists()) {
				if (!file.mkdirs()) {
					return;
				}					
			}
			file = new File(fileName);
			if (file.exists()) {
				file.delete();
			}				
		}
	}

	public FileItem getItem() {
		return item;
	}

}
